<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\BrandRecommendedToday;
use Biz\service\brand\BrandRecommendedTodayService;
use Biz\model\brand\Brand;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class BrandRecommendedTodayController extends Controller
{
    const PAGE_SIZE = 20;
    const DEFAULT_HAOHAOZHU_UID = 11941;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \Encore\Admin\Layout\Content $content
     * @return \Encore\Admin\Layout\Content
     */
    public function index(Request $request, Content $content): Content
    {
        $brand_list = BrandRecommendedTodayService::getBrandRecommendedTodayList();
        $count = (int)count($brand_list);
        $gridModel = new pGridDataModel($brand_list, $count, []);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->column('id', 'ID')->sort();
            $grid->column('brand_id', '品牌ID');
            $grid->column('brand_name', '品牌名称');
            $grid->column('logo', '品牌logo')->display(function () {
                if ($this->logo) {
                    return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->logo,
                            ImgUrl::IMAGE_SIZE_SQ_PHONE)."' width=300 />";
                } else {
                    "<img src='".\Biz\service\brand\Brand::BRAND_DEFAULT_LOGO."' width=300 />";
                }

            })->width(350);
            $grid->column('addtime', '添加时间')->date('Y-m-d H:i:s');
            $grid->column('edittime', '修改时间')->date('Y-m-d H:i:s');
            $grid->column('status', '状态')->display(function () {
                if ($this->status == 1) {
                    return '<span style="color:yellowgreen">正常</span>';
                } else {
                    return '<span style="color:red">删除</span>';
                }
            });
        });

        return $content
            ->header('今日推荐品牌管理')
            ->body($listGrid);

    }

    /**
     * 添加
     * @param \Illuminate\Http\Request $request
     * @param \Encore\Admin\Layout\Content $content
     * @return \Encore\Admin\Layout\Content
     */
    public function add(Request $request, Content $content): Content
    {
        $request = $request->all();

        return $content
            ->header('添加banner')
            ->breadcrumb(
                ['text' => '今日推荐品牌管理', 'url' => '/brand/recommendedTodayList'],
                ['text' => '添加今日推荐品牌', 'url' => '/brand/recommendedTodayList/create']
            )
            ->body(self::editAction($request, $id = 0));

    }


    /**
     * 修改
     * @param $request
     * @param int $id
     * @return string
     */
    public function editAction($request, $id = 0): string
    {
        $data = [];
        if ($id != 0) {
            //修改
            $data = BrandRecommendedToday::getInfo(['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            //添加
            $form = new Form($data);
        }
        $arr = Brand::getAllBrandForRecommend();
        $arr = array_column($arr, 'brand_name', 'id');
        $form->select("brand_id", '今日推荐品牌')->options($arr);
        $form->action('/admin/brand/recommendedTodayList/save');

        return $form->render();
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param \Encore\Admin\Layout\Content $content
     * @param $id
     * @return \Encore\Admin\Layout\Content
     */
    public function edit(Request $request, Content $content, $id): Content
    {

        $request = $request->all();

        return $content
            ->header('今日推荐品牌管理')
            ->breadcrumb(
                ['text' => '今日推荐品牌管理', 'url' => '/rand/recommendedTodayList'],
                ['text' => '修改今日推荐品牌', 'url' => '/brand/recommendedTodayList/'.$id.'/edit']
            )
            ->body(self::editAction($request, $id));
    }


    /**
     * 提交
     * @param \Illuminate\Http\Request $request
     * @param \Encore\Admin\Layout\Content $content
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function save(Request $request, Content $content)
    {
        $request = $request->all();

        $data['brand_id'] = $request['brand_id'];
        $data['admin_id'] = Admin::user()->id;
        $rs = false;
        $msg = '';

        $info = BrandRecommendedToday::getInfo([
            'brand_id' => $request['brand_id'],
            'recommended_today_status' => BrandRecommendedToday::STATUS_NORMAL,
        ]);
        $id = $info['id'] ?? 0;
        if (isset($request['id']) && $request['id']) {

            if ($id > 0 && $id != $request['id']) {
                $msg = '，该品牌已存在';
            } else {
                $data['edittime'] = date('Y-m-d H:i:s', time());
                //修改
                $rs = BrandRecommendedToday::updateData($data, ['id' => $request['id']]);
            }
        } else {
            $count = BrandRecommendedToday::count(['recommended_today_status' => BrandRecommendedToday::STATUS_NORMAL]);
            if ($count >= 3) {
                $msg = '，推荐品牌只能配置三个';
            } else {
                if ($id > 0) {
                    $msg = '，该品牌已存在';
                } else {
                    //添加
                    $data['addtime'] = date('Y-m-d H:i:s', time());
                    $rs = BrandRecommendedToday::insertData($data);
                }
            }

        }

        if ($rs) {
            $success = new MessageBag([
                'title' => '提交成功',
            ]);

            return redirect('/admin/brand/recommendedTodayList')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '提交失败'.$msg,
            ]);

            return redirect('/admin/brand/recommendedTodayList')->with(compact('error'));
        }
    }

    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function del($id): JsonResponse
    {
        $data = BrandRecommendedToday::getInfo(['id' => $id]);
        if ($data) {
            $data['recommended_today_status'] = BrandRecommendedToday::STATUS_DELETE;
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $data['admin_id'] = Admin::user()->id;
            $rs = BrandRecommendedToday::updateData($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    /**
     * 拖动排序
     * @param Request $request
     */
    public function sort(Request $request)
    {
        $request = $request->all();
        $sorts = $request['sort'];
        if ($sorts && is_array($sorts)) {
            foreach ($sorts as $id => $sort) {
                $data['recommended_today_sort'] = $sort;
                $data['edittime'] = date('Y-m-d H:i:s', time());
                BrandRecommendedToday::updateData($data, ['id' => $id]);
            }
        }
    }

}
